<template>
  <div class="mdv-app-index">
    <canvas id="canvas-ban" class="canvas"></canvas>
    <canvas id="canvas" class="canvas"></canvas>

    <mdv-header v-show="!!token"></mdv-header>
    <transition name="page-change" mode="out-in">
      <router-view></router-view>
    </transition>
  </div>
</template>

<script>
import store from '@/stores/'

import header from '@/pages/App/Header'

import Stars from '@/assets/script/Star'
import Moon from '@/assets/script/Moon'
import Meteor from '@/assets/script/Meteor'
import Ban from '@/assets/script/Ban'

export default {
  name: 'MdvAppIdx',
  props: [],
  mixins: [],
  data () {
    return {
    }
  },
  computed: {
    token () {
      return store.state.common.token
    }
  },
  created () {
  },
  mounted () {
    this.canvas()
  },
  methods: {
    canvas () {
      console.log('mdv' || Ban)
      let canvas = document.getElementById('canvas')
      let ctx = canvas.getContext('2d')
      let width = window.innerWidth
      let height = window.innerHeight
      // 实例化月亮和星星。流星是随机时间生成，所以只初始化数组
      let moon = new Moon(ctx, width, height)
      let stars = new Stars(ctx, width, height, 200)
      let meteors = []
      let count = 0

      canvas.width = width
      canvas.height = height

      const meteorGenerator = () => {
        // x位置偏移，以免经过月亮
        let x = Math.random() * width + 800
        meteors.push(new Meteor(ctx, x, height))

        // 每隔随机时间，生成新流星
        setTimeout(() => {
          meteorGenerator()
        }, Math.random() * 2000)
      }

      const frame = () => {
        count++
        count % 10 === 0 && stars.blink()
        // ban.draw()
        moon.draw()
        stars.draw()

        meteors.forEach((meteor, index, arr) => {
          // 如果流星离开视野之内，销毁流星实例，回收内存
          if (meteor.flow()) {
            meteor.draw()
          } else {
            arr.splice(index, 1)
          }
        })
        window.requestAnimationFrame(frame)
      }
      meteorGenerator()
      frame()
    }
  },
  components: {
    MdvHeader: header
  }
}
</script>

<style lang="scss">
.mdv-app-index {
  width: 100%;
  height: 100%;
  color: #FFF;
  padding-top: 50px;
  text-align: center;

  #canvas{
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: -2;
  }
  #canvas-ban {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: -1;
  }
}
</style>
